package org.example.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ModelQuery;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RequestMapping("/model")
@Controller
@Slf4j
public class ModelerController {
    @Resource
    private RepositoryService repositoryService;

    //模型创建
    @RequestMapping("/create")
    public void create(HttpServletRequest request, HttpServletResponse response) {
        try {
            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

            RepositoryService repositoryService = processEngine.getRepositoryService();

            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.put("stencilset", stencilSetNode);
            //新建模型
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, "testactivity1");
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            String description = "自定义审批流测试1";
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName("自定义审批流测试1");
            modelData.setKey("74185296339");

            //保存模型
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
        } catch (Exception e) {
            System.out.println("创建模型失败：");
        }
    }

    //根据模型id部署流程
    @RequestMapping("/deploy")
    public void deploy(String modelId) throws IOException {
        // 获取模型
        Model model = repositoryService.getModel(modelId);
        ObjectNode objectNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(model.getId()));
        BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(objectNode);

        String processName = model.getName()+".bpmn20.xml";
        byte[] bytes = new BpmnXMLConverter().convertToXML(bpmnModel);
        // 部署流程
        Deployment deployment = repositoryService
                .createDeployment().name(model.getName())
                .addString(processName, new String(bytes,"UTF-8"))
                .deploy();
    }

    //模型列表
    @RequestMapping("/list")
    @ResponseBody
    public List list(HttpServletRequest request) {
        log.info("-------------模型列表-------------");
        ModelQuery modelQuery = repositoryService.createModelQuery();
        String keyWord = request.getParameter("keyWord");//搜索关键字
        if (StringUtils.isNotBlank(keyWord)){
            modelQuery.modelNameLike("%"+keyWord+"%");
        }
        List<Model> models = modelQuery.orderByCreateTime().desc().list();
        return models;
    }
}
